/**
 * Created by Administrator on 2019-03-20.
 */
var reportModelUtil = {
    panelId:"",
    renderArray:[],
    myChartArray : [],
    downLoadTmp:function(panelId){//下载模板文件
        var indexLoad =  layer.load()
        var url = basePath+"/xdWidgetPanel/createExcelTmp?panelId="+panelId ;
        $.getJSON(url,function(rst){
            layer.close(indexLoad)
            //console.log(rst)
            if(rst.code == 0){
                window.open(basePath+"/specialDownLoad/doXLSXByTempFileAndFileName?fileName="+rst.data.fileName +"&tempFile="+rst.data.tempFile)
            }else{
                layer.alert("下载异常：<br>"+rst.msg,{icon:2})
            }
        })
    },
    upLoadXLSX:function(panelId,upload,layid){
        var upDom =   $("div[lay-id="+layid+"] .layui-table-tool-temp").find("button[lay-event=upLoad]")
        upload.render({elem:upDom,
            url:basePath+"/specialUpLoad/doUpdLoadXdPanelDataByXLSX",
            data:{panelId:panelId},
            accept:"file",
            exts:"xlsx",
            acceptMime:"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
            before: function(obj){ //obj参数包含的信息，跟 choose回调完全一致，可参见上文。
                layer.load()
            },
            done:function(res){
                layer.closeAll()
                //console.log(res)
                if(res.code !=0){
                    layer.alert(res.msg)
                }else{
                    layer.msg("文件上传成功，正在写入表...",{icon:6},function(){
                        layer.load()
                        $.getJSON(basePath+"/specialUpLoad/importXlsx2TableByPanelId",{tempFile:res.data,panelId:panelId},function(rst){
                            layer.alert(rst.msg,{icon: 6},function(){
                                layer.closeAll()
                            })
                        })
                    })
                }
            },
            error:function(){
                layer.alert("上传文件异常，请重试",function(){
                    layer.closeAll()
                })
            }
        })
    },

    initTable:function(form,table,tableArray,upload,where){//初始化table

        $.each(tableArray,function(index,tableOption){
            tableOption.where = where
            //console.log(tableOption)
            tableOption.done = function(res, curr,count){
                if(!tableOption.page){
                    commonUtil.mergeCell(tableOption.id,tableOption.mergeField)
                }
                reportModelUtil.upLoadXLSX(tableOption.widgetPanelId,upload,tableOption.id)
            }

            //进入页面查询
            if(tableOption.queryFlag){
                table.render(tableOption)
            }

            //自动查询
            if(tableOption.autoFlag){
                setInterval(function(){
                    table.render(tableOption)
                },(1000*60) * tableOption.autoInterval );
            }

            //监听表头工具栏
            table.on("toolbar("+tableOption.id+")",function(obj){
                var event = obj.event;
                var checkStatus = table.checkStatus(obj.config.id);
                var checkCount = checkStatus.data.length

                switch (event){
                    case "downLoad"://下载
                        form.on("submit(down2007)",function(objs){
                            //console.log(objs.field)
                            var indexLoad =  layer.load()
                            var url = basePath+"/xdWidgetPanel/createExcel2007?panelId="+ tableOption.widgetPanelId;
                            $.post(url,objs.field,function(rst){
                                layer.close(indexLoad)
                                //console.log(rst)
                                if(rst.code == 0){
                                    window.open(basePath+"/specialDownLoad/doXLSXByTempFileAndFileName?fileName="+tableOption.title +"&tempFile="+rst.data.tempFile)
                                }else{
                                    layer.alert("下载异常：<br>"+rst.msg,{icon:2})
                                }
                            },"json")
                        })
                        $("[lay-filter=down2007]").click()
                        break;
                    case "downLoadTmp":
                        //console.log(event,panelId)
                        reportModelUtil.downLoadTmp(tableOption.widgetPanelId)
                        break;
                    case "upLoad":
                        break;
                    case "del":
                        if(checkCount <=0){
                            layer.msg("请先选择一条记录后再操作",{icon:5})
                        }else{
                            layer.confirm("确定要删除该记录吗？",{icon:3,title:tableOption.title},function(index){
                                layer.close(index);
                                var param = checkStatus.data[0]
                                param.widgetPanelId = tableOption.widgetPanelId
                                $.getJSON(basePath+"/xdWidgetPanel/del",param,function(rst){
                                    if(rst.code !=0){
                                        layer.alert(rst.msg,{icon: 1},function(index1){
                                            layer.close(index1)
                                        })
                                    }else{
                                        layer.msg(rst.msg)
                                        table.render(tableOption)
                                    }
                                })
                            })
                        }
                        break;
                    case "add":
                        commonUtil.openPage("新增："+tableOption.title,basePath+"/xdWidgetPanel/add?widgetPanelId="+ tableOption.widgetPanelId )
                        break;
                    case "edit":
                        if(checkCount <=0){
                            layer.msg("请先选择一条记录后再操作",{icon:5})
                        }else{
                            var param = checkStatus.data[0]
                            param.widgetPanelId = tableOption.widgetPanelId
                            var jsonStr = encodeURIComponent(JSON.stringify(param))
                            commonUtil.openPage("编辑："+tableOption.title,basePath+"/xdWidgetPanel/edit?jsonStr="+ jsonStr )
                        }
                        break;
                }
            })

        })
    },
    initSelect:function(formSelects,allSelect,eventMap,selectValue){//初始化select
        selectValue = selectValue || {}
        $.each(allSelect,function(key,item){//先初始化
            if(item.serverFlag){
                formSelects.data(item.name, 'server', {//远程根据 keyword 查询
                    type:"post",
                    data:{id:item.id,initData:selectValue[item.name]},
                    searchUrl:basePath+"/xdWidgetSelect/selectView"
                });
            }else{
                var value = [selectValue[item.name]]
                if(item.radio != "true"){
                    value = selectValue[item.name].split(",")
                }
                formSelects.render(item.name,{init:  value})
            }
        })

        $.each(eventMap,function(eventSelect,item){//添加级联事件
            formSelects.on(eventSelect, function(id, vals, val, isAdd, isDisabled){
                var valueAarray = {}
                $.each(item.events.split(";"),function(index,targetSelect){
                    var eventValue = formSelects.value(eventSelect , 'valStr' )
                    valueAarray[eventSelect] = eventValue
                    if(allSelect[targetSelect] != null){
                        if(allSelect[targetSelect].serverFlag){
                            valueAarray.id = allSelect[targetSelect].id
                            //initData 初始赋值
                            valueAarray.initData = selectValue[targetSelect]
                            formSelects.config(targetSelect, {
                                data:valueAarray
                            }).data(targetSelect, 'server', {
                                url:basePath+"/xdWidgetSelect/selectView"
                            });
                        }else{
                            formSelects.search(targetSelect,selectValue[targetSelect] || eventValue);
                        }
                    }
                })
            },true);
        })
    },
    initEchart: function (form,echartArray ,actionParams) {//初始化Echart配置
        var chartIdArray = []
        var initHeight = window.innerHeight
        $.each(echartArray,function(index,option){
            var actionParam = actionParams[index]||{}
            var chartId = actionParam.domId
            chartIdArray.push("#dom-"+chartId)
            $("#dom-"+chartId).height(initHeight* actionParam.height * 0.01)
            var myChart = echarts.init(document.getElementById("dom-"+chartId));

            if(actionParam.queryFlag ){
                var formValue = commonUtil.getFormValueNormal('form[lay-filter="rpt-form"]')
                formValue.panelId = option.panelId
                reportModelUtil.renderMyChart(myChart,option,formValue,actionParam.height)
            }

            if(actionParam.autoFlag == true){
                setInterval(function(){
                    var formValue = commonUtil.getFormValueNormal('form[lay-filter="rpt-form"]')
                    formValue.panelId = option.panelId
                    reportModelUtil.renderMyChart(myChart,option,formValue,actionParam.height)
                },(1000*60) * actionParam.autoInterval );
            }

            reportModelUtil.bindEchartAction(myChart,actionParam)

            reportModelUtil.myChartArray.push(myChart)
        })

    },
    renderMyChart:function(myChart,option,formValue,height){//生成chart-series并画图

        $.post(basePath+"/xdWidgetPanel/queryPanelEchartData"+urlParam,formValue||{}, function (rst) {
            if(rst.code == 0){
                //console.log(JSON.stringify(rst.data))
                //card-body-7-1555666770340
                //$("#dom-"+option.panelId ).height( window.innerHeight * height * 0.01)
                //myChart.resize();
                option.series = rst.data
                myChart.setOption(option)

            }else{
                layer.alert(rst.msg)
            }
        },'json')
    },
    bindBTAction:function(form,table,tableArray,echartArray,actionParams){

        form.on("submit(rpt-query)", function (obj) {
            var dataValue = obj.field;
            $.each(tableArray,function(index,tableOption){
                tableOption.where = dataValue
                //tableOption.page = {curr: 1}
                table.render(tableOption)
            })

            $.each(reportModelUtil.myChartArray,function(index,chartItem){
                dataValue.panelId = echartArray[index].panelId
                reportModelUtil.renderMyChart(chartItem,echartArray[index],dataValue,actionParams[index].height)
            })

        })
    },
    bindEchartAction:function(myChart,actionParams){//echart事件

        if(actionParams.echartAction){
            myChart.on("click",function(params){
                var url = actionParams.echartAction
                var chartParam = [ "seriesName", "name", "value" ]
                var formValue = commonUtil.getFormValueNormal('form[lay-filter="rpt-form"]')
                $.each(actionParams,function(key,value){
                    var pstr="&"+key+"="
                    if($.inArray(value, chartParam) !=-1 ){
                        if(value=="value" && url.indexOf(pstr) < 0){
                            url = url + pstr + (params[value][1] == undefined ? params[value] : params[value][1])
                        }else{
                            url = url + pstr + params[value]
                        }
                    }else if(value=="condition" && url.indexOf(pstr) < 0 ){
                        url = url + pstr + (formValue[key] == undefined ?'':formValue[key])
                    }
                })
                commonUtil.openPage('',url)
            })
        }
    }
}